# -*- coding: utf-8 -*-
import urllib.request
import urllib.parse
import html.parser as h
import http.cookiejar
import re
import time
import datetime
import os

cookie = http.cookiejar.CookieJar()
baseUrl = "https://cn.neworld.date/"
nowEmail = None
passwd = 'liang123'
with open("./nowEmail", 'r+') as nowEmailFile:
    nowEmail = nowEmailFile.readlines()
    nowEmail = str(int(nowEmail[-1])+1)
    nowEmailFile.write(nowEmail+"\n")

print("nowEmail:", nowEmail)

#请求url
def curl(regUrl, data = None, method = None, headers={}):
    headers = {'Origin':'https://cn.neworld.date',
               'Content-Type':'application/x-www-form-urlencoded; charset=UTF-8', **headers}
    if data:
        data = bytes(urllib.parse.urlencode(data),  encoding='utf8')
    method = 'POST' if data is not None and method is None else method

    handler = urllib.request.HTTPCookieProcessor(cookie)  # 利用urllib2库的HTTPCookieProcessor对象来创建cookie处理器
    opener = urllib.request.build_opener(handler)  # 通过handler来构建opener
    req = urllib.request.Request(regUrl, data = data,
                                 headers=headers, method=method
                                 )
    with opener.open(req) as ret:
        return ret.read().decode()
#写入剪切板
def setClipboard(data):
    os.system(r'ECHO %s|CLIP' % data)


getCodeUrl = baseUrl + 'code'
regUrl = baseUrl + 'auth/register'
loginUrl = baseUrl + 'auth/login'
checkinUrl = baseUrl + 'user/checkin'
userUrl = baseUrl + 'user'

'获得code'
codeRes = curl(getCodeUrl)
code = re.search(r'<a href="\/auth\/register\?code=(\w+)">', codeRes, re.I).group(1)
print("code:", code)
'注册'
regRet = curl(regUrl, {'email':nowEmail+'@qq.com',
                                   'name':nowEmail,
                                   'passwd':passwd,
                                   'repasswd':passwd,
                                   'wechat':nowEmail,
                                   'imtype':'2',
                                   'code':code})
print('注册:',regRet)
'登录'
loginRet = curl(loginUrl, {'email':nowEmail+'@qq.com', 'passwd': passwd, 'remember_me':'week'})
print('登录:',loginRet)
'签到'
checkinRet = curl(checkinUrl, method="POST")
print('签到:',checkinRet)
'获取订阅地址'
userRet = curl(userUrl)
rssUrl = re.search('订阅地址：<code>(.+)</code>', userRet).group(1);
print('rssUrl:', rssUrl)
setClipboard(rssUrl)
with open("./rssUrlS.txt", 'a') as rssFile:
    rssFile.write("%s %s %s:\n%s\n" % (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'), nowEmail, passwd, rssUrl))
print("done------------------------------------------------------------------------------------------------")
time.sleep(10)